package io.alvin.ch02;

import java.util.ArrayList;
import java.util.Vector;

/**
 * 多线程中使用ArrayList，导致错误发生。
 * 程序可能得出错误的结果，或者抛出ArrayIndexOutOfBoundsException原因是ArrayList扩容出现内部一致性被破坏。
 * 替代方法：可以使用Vector替代ArrayList。
 *
 * Created by Alvin on 2017/7/7.
 */
public class ArrayListMultiThread {

    //static ArrayList<Integer> al = new ArrayList<>(10);
    static Vector<Integer> al = new Vector<>();

    public static class AddThread implements Runnable {

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            for (int i = 0; i < 1_000_000; i++) {
                al.add(i);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new AddThread());
        Thread t2 = new Thread(new AddThread());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(al.size());
    }
}
